#pragma once
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <jsoncpp/json/json.h>
#include <memory>
// using namespace std;

namespace aod
{
    class FileUtil
    {
    public:
        FileUtil(const std::string &name)
            : _name(name)
        {
        }
        bool IsExist() // 判断文件是否存在
        {
            return 0 == access(_name.c_str(), F_OK);
        }
        size_t size() // 放回文件大小
        {
            if (!IsExist())
                return 0;
            struct stat s;
            int ret = stat(_name.c_str(), &s);
            return s.st_size;
        }
        bool CreateDirectory() // 创建目录
        {
            if (!IsExist())
            {
                mkdir(_name.c_str(), 0777);
            }
            return true;
        }
        bool SetContent(const std::string &body) // 向文件中写入数据
        {
            std::ofstream ofs(_name, std::ios::binary);
            if (!ofs.is_open())
            {
                std::cout << "打开文件失败" << std::endl;
                return false;
            }
            ofs.write(body.c_str(), body.size());
            ofs.close();
            return true;
        }
        void GetContent(std::string *body) // 读取文件内容
        {
            std::ifstream ifs(_name, std::ios::binary);
            if (!ifs.is_open())
            {
                std::cout << "打开文件失败" << std::endl;
                return;
            }
            size_t sz = size();
            body->resize(sz);
            ifs.read(&(*body)[0], sz);
            ifs.close();
        }

    private:
        std::string _name;
    };

    class JsonUtil
    {
    public:
        static bool Serialize(const Json::Value &root, std::string *s)
        {
            Json::StreamWriterBuilder swb;
            std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
            std::stringstream ss;
            int ret = sw->write(root, &ss);
            if (ret != 0)
            {
                std::cout << "Serialize failed" << std::endl;
                return false;
            }
            *s = ss.str();
            return true;
        }
        static bool UnSerialize(Json::Value *root, const std::string &s)
        {
            Json::CharReaderBuilder crb;
            std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
            std::string err;
            bool ret = cr->parse(s.c_str(), s.c_str() + s.size(), root, &err);
            if(ret == false)
            {
                std::cout << "Unserialize failed" << std::endl;
                return false;
            }
            return true;
        }
    };
}